package com.zdkj.subway.stm.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.admin.api.entity.SysDictItem;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.core.util.R;
import com.zdkj.common.data.mybatis.wrapper.CustomQueryWrapper;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.stm.constant.StmConstans;
import com.zdkj.subway.stm.dto.out.SwStSpecialCardApplyDTO;
import com.zdkj.subway.stm.entity.SwStCycleApply;
import com.zdkj.subway.stm.entity.SwStSpecialCardApply;
import com.zdkj.subway.stm.fegin.SystemUserService;
import com.zdkj.subway.stm.mapper.SwStSpecialCardApplyMapper;
import com.zdkj.subway.stm.service.SwStSpecialCardApplyService;
import com.zdkj.subway.stm.util.BeanPropertyUtils;
import com.zdkj.subway.stm.util.LocalDateTimeConverter;
import com.zdkj.subway.stm.util.UploadDataListener;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 特殊工作卡申请信息表
 *
 * @author cuilei
 * @date 2020-05-26 10:48:18
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/swstspecialcardapply")
@Api(value = "swstspecialcardapply", tags = "特殊工作卡申请信息表管理")
public class SwStSpecialCardApplyController {

    private final SwStSpecialCardApplyService swStSpecialCardApplyService;
    private final SystemUserService systemUserService;
    @Resource
    SwStSpecialCardApplyMapper swStSpecialCardApplyMapper;

    /**
     * 分页查询
     *
     * @param page                 分页对象
     * @param swStSpecialCardApply 特殊工作卡申请信息表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwStSpecialCardApplyPage(Page page, SwStSpecialCardApply swStSpecialCardApply) {
        PigxUser user = SecurityUtils.getUser();
        String dateCondition = swStSpecialCardApply.getApplyTimeDTO();
        List<String> dateConditionRange = swStSpecialCardApply.getDates1();

        LambdaQueryWrapper<SwStSpecialCardApply> queryWrapper = Wrappers.query(swStSpecialCardApply).orderByDesc("apply_time").
                lambda();
        if (StringUtils.isNotBlank(dateCondition)) {
            queryWrapper.likeRight(SwStSpecialCardApply::getApplyTime, dateCondition);
        }

        if (ObjectUtil.isNotEmpty(dateConditionRange)) {
            queryWrapper.between(SwStSpecialCardApply::getApplyTime, dateConditionRange.get(0), dateConditionRange.get(1));
        }
        if (!user.getBelongToLine()) {
            return R.ok(swStSpecialCardApplyService.page(page, queryWrapper.eq(SwStSpecialCardApply::getStationCode, user.getStationCode())));
        }
        return R.ok(swStSpecialCardApplyService.page(page, queryWrapper.eq(SwStSpecialCardApply::getSubmitStatus, CommonConstants.SUBMIT)));
    }

    /**
     * 通过id查询特殊工作卡申请信息表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swStSpecialCardApplyService.getById(id));
    }

    /**
     * 新增特殊工作卡申请信息表
     *
     * @param swStSpecialCardApply 特殊工作卡申请信息表
     * @return R
     */
    @ApiOperation(value = "新增特殊工作卡申请信息表", notes = "新增特殊工作卡申请信息表")
    @SysLog("新增特殊工作卡申请信息表")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('stm_sw_st_special_card_apply_add')")
    public R save(@RequestBody SwStSpecialCardApply swStSpecialCardApply) {
        SwStSpecialCardApply defaultObj = ObjectUtils.getDefaultObj(SwStSpecialCardApply.class);
        BeanUtils.copyProperties(swStSpecialCardApply, defaultObj,
                BeanPropertyUtils.getNullAndEmptyPropertyNames(swStSpecialCardApply));
        return R.ok(swStSpecialCardApplyService.save(defaultObj));
    }

    /**
     * 修改特殊工作卡申请信息表
     *
     * @param swStSpecialCardApply 特殊工作卡申请信息表
     * @return R
     */
    @ApiOperation(value = "修改特殊工作卡申请信息表", notes = "修改特殊工作卡申请信息表")
    @SysLog("修改特殊工作卡申请信息表")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('stm_sw_st_special_card_apply_edit')")
    public R updateById(@RequestBody SwStSpecialCardApply swStSpecialCardApply) {
        return R.ok(swStSpecialCardApplyService.updateById(swStSpecialCardApply));
    }

    /**
     * 通过id删除特殊工作卡申请信息表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除特殊工作卡申请信息表", notes = "通过id删除特殊工作卡申请信息表")
    @SysLog("通过id删除特殊工作卡申请信息表")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_special_card_apply_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swStSpecialCardApplyService.removeById(id));
    }

    /**
     * 批量删除
     * @param idList
     * @return
     */
    @SysLog("通过id批量删除特殊工作卡申请")
    @DeleteMapping("/delBatchObj")
    @Transactional
    @ApiOperation(value = "通过id批量删除特殊工作卡申请", notes = "通过id批量删除特殊工作卡申请")
    public R batchRemoveById(@RequestBody List<Integer> idList) {
        List<SwStSpecialCardApply> list = swStSpecialCardApplyService.list(new QueryWrapper<SwStSpecialCardApply>().lambda().in(SwStSpecialCardApply::getId, idList));
        List<Integer> deleteIds = list.stream().filter(x -> !x.getSubmitStatus().equals(CommonConstants.SUBMIT)).map(x -> x.getId()).collect(Collectors.toList());
        if(CollectionUtil.isEmpty(deleteIds)){
            return R.failed(StmConstans.failedDelete);
        }
        deleteIds.forEach(swStSpecialCardApplyService::removeById);
        return R.ok();
    }
    /**
     * 批量提交特殊工作卡申请
     *
     * @param idList
     * @return
     */
    @ApiOperation(value = "批量提交特殊工作卡申请", notes = "批量提交特殊工作卡申请")
    @SysLog("批量提交特殊工作卡申请")
    @PostMapping("/submit")
    @PreAuthorize("@pms.hasPermission('stm_sw_st_special_card_apply_submit')")
    public R submit(@RequestBody List<Integer> idList) {
        List<SwStSpecialCardApply> submitList = new ArrayList<>();
        idList.forEach(id -> {
            SwStSpecialCardApply submitItem = new SwStSpecialCardApply();
            submitItem.setId(id);
            submitItem.setSubmitStatus(CommonConstants.SUBMIT);
            submitList.add(submitItem);
        });
        return R.ok(swStSpecialCardApplyService.updateBatchById(submitList));
    }

    /**
     * 批量审核特殊工作卡
     *
     * @param auditList
     * @return
     */
    @ApiOperation(value = "批量审核特殊工作卡", notes = "批量审核特殊工作卡")
    @SysLog("批量审核特殊工作卡")
    @PutMapping("/audit")
    public R audit(@RequestBody List<SwStSpecialCardApply> auditList) {
        List<SwStSpecialCardApply> audit = new ArrayList<>();
        auditList.forEach(item -> {
            if (CommonConstants.UN_SUBMIT.equals(item.getSubmitStatus())) {
                log.info("未提交申请无法审核！");
            } else {
                PigxUser user = SecurityUtils.getUser();
                item.setCheckPersonName(user.getNikeName());
                item.setCheckPersonCode(user.getUserCode());
                item.setCheckTime(LocalDateTime.now());
                audit.add(item);
            }
        });
        return R.ok(swStSpecialCardApplyService.updateBatchById(audit));
    }

    /**
     * 导出特殊工作卡申请
     *
     * @param ids
     * @param response
     * @return
     */
    @ApiOperation(value = "导出特殊工作卡申请", notes = "导出特殊工作卡申请")
    @SysLog("导出特殊工作卡申请")
    @GetMapping("/export")
    public void exportExcel(@RequestParam(value = "ids") List<Integer> ids, HttpServletResponse response) throws IOException {
        List<SwStSpecialCardApply> records;
        PigxUser user = SecurityUtils.getUser();
        if(CollectionUtils.isNotEmpty(ids)){
            records = swStSpecialCardApplyMapper.selectBatchIds(ids).stream().sorted(Comparator.comparing(SwStSpecialCardApply::getApplyTime).reversed()).collect(Collectors.toList());
        }else{
            if(!user.getBelongToLine()){
                QueryWrapper<SwStSpecialCardApply> wrapper = new QueryWrapper<>();
                wrapper.lambda().eq(SwStSpecialCardApply::getLineCode,user.getLineCode())
                        .eq(SwStSpecialCardApply::getStationCode,user.getStationCode())
                        .eq(SwStSpecialCardApply::getDelFlag,"0")
                        .orderByDesc(SwStSpecialCardApply::getApplyTime);
                records = swStSpecialCardApplyService.list(wrapper);
            }else {
                QueryWrapper<SwStSpecialCardApply> wrapper = new QueryWrapper<>();
                wrapper.lambda().eq(SwStSpecialCardApply::getSubmitStatus,CommonConstants.SUBMIT)
                        .eq(SwStSpecialCardApply::getDelFlag,"0")
                        .orderByDesc(SwStSpecialCardApply::getApplyTime);
                records = swStSpecialCardApplyService.list(wrapper);
            }
        }
        /*Page page = new Page();
        page.setSize(-1);
        PigxUser user = SecurityUtils.getUser();
        String dateCondition = swStSpecialCardApply.getApplyTimeDTO();
        CustomQueryWrapper<SwStSpecialCardApply> customQueryWrapper = new CustomQueryWrapper(SwStSpecialCardApply.class)
                .addDTO(swStSpecialCardApply).addAlis("a").addDelFlag(Boolean.TRUE).init();
        if (StringUtils.isNotBlank(dateCondition)) {
            customQueryWrapper.likeRight("APPLY_TIME", dateCondition);
        }
        if (!user.getBelongToLine()) {
            customQueryWrapper.eq("STATION_CODE", user.getStationCode());
        } else {
            customQueryWrapper.eq("SUBMIT_STATUS", CommonConstants.SUBMIT);
        }
        List<SwStSpecialCardApplyDTO> exportList = swStSpecialCardApplyService.pageSelect(page, customQueryWrapper).getRecords();*/
        try {
            R<List<SysDictItem>> inputDataStatus = systemUserService.getDictByType(StmConstans.SUBMIT_STATUS);
            R<List<SysDictItem>> inputDataStatus1 = systemUserService.getDictByType(StmConstans.AUDIT_STATUS);
            List<SysDictItem> dictData = inputDataStatus.getData();
            List<SysDictItem> dictData1 = inputDataStatus1.getData();
            for (SwStSpecialCardApply record : records) {
                Map<String, String> map = dictData.stream().collect(Collectors.toMap(SysDictItem::getValue, SysDictItem::getLabel));
                Map<String, String> map1 = dictData1.stream().collect(Collectors.toMap(SysDictItem::getValue, SysDictItem::getLabel));
                record.setSubmitStatus(map.get(record.getSubmitStatus()));
                record.setCheckStatus(map1.get(record.getCheckStatus()));
            }
            String fileName = URLEncoder.encode("特殊工作卡申请", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SwStSpecialCardApplyDTO.class).registerConverter(new LocalDateTimeConverter())
                    .sheet("特殊工作卡申请").doWrite(records);
        } catch (IOException e) {
            log.error("导出车票盘点数据失败");
        }
    }

    /**
     * 导入特殊工作卡申请
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "导入特殊工作卡申请", notes = "导入特殊工作卡申请")
    @SysLog("导入特殊工作卡申请")
    @PostMapping("/import")
    public R importExcel(@RequestParam("file") MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), SwStSpecialCardApply.class,
                    new UploadDataListener(swStSpecialCardApplyService, SwStSpecialCardApply.class))
                    .sheet().doRead();
            return R.ok("导入成功");
        } catch (IOException e) {
            log.info(e.getMessage());
            return R.ok("导入失败");
        }
    }
}
